package com.gzwanchuang.xhgj.ui.page.mine;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.lifecycle.ViewModelProviders;

import com.google.protobuf.InvalidProtocolBufferException;
import com.gzwanchuang.architecture.utils.GsonUtils;
import com.gzwanchuang.architecture.utils.Utils;
import com.gzwanchuang.architecture.utils.ValidateUtils;
import com.gzwanchuang.xhgj.R;
import com.gzwanchuang.xhgj.bridge.data.repository.Apis;
import com.gzwanchuang.xhgj.bridge.request.LoginRequestViewModel;
import com.gzwanchuang.xhgj.bridge.state.home.TiErRenViewModel;
import com.gzwanchuang.xhgj.bridge.state.home.XiangHuiRenViewModel;
import com.gzwanchuang.xhgj.databinding.FragmentTiErRenBinding;
import com.gzwanchuang.xhgj.databinding.FragmentXiangHuiRenBinding;
import com.gzwanchuang.xhgj.net.NetworkManager;
import com.gzwanchuang.xhgj.net.interfaces.OnRequestCallBack;
import com.gzwanchuang.xhgj.proto.Bank;
import com.gzwanchuang.xhgj.proto.Merchantservice;
import com.gzwanchuang.xhgj.ui.base.BaseFragment;
import com.gzwanchuang.xhgj.ui.dialog.RecycleViewDialog;
import com.gzwanchuang.xhgj.ui.dialog.SelectMonthDialog;
import com.tencent.ocr.sdk.common.ISdkOcrEntityResultListener;
import com.tencent.ocr.sdk.common.OcrSDKKit;
import com.tencent.ocr.sdk.common.OcrType;
import com.tencent.ocr.sdk.entity.BankCardOcrResult;

import java.util.List;

import kale.ui.view.dialog.EasyDialog;

/**
 * 文件名 : HomeRootFragment
 * 创建者 : MangoWang
 * 创建日期 : 2019/12/24 16:20
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */
public class XiangHuiRenFragment extends BaseFragment {
    private FragmentXiangHuiRenBinding mBinding;
    private XiangHuiRenViewModel mViewModel;
    private LoginRequestViewModel mRequestViewModel;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mViewModel = ViewModelProviders.of(this).get(XiangHuiRenViewModel.class);
        mRequestViewModel = ViewModelProviders.of(this).get(LoginRequestViewModel.class);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_xiang_hui_ren, container, false);
        mBinding = FragmentXiangHuiRenBinding.bind(view);
        mBinding.setClick(new ClickProxy());
        mBinding.setVm(mViewModel);
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mRequestViewModel.getErrorString().observe(this, s -> {
            showShortToast(s);
        });

        mRequestViewModel.getResultString().observe(this, s -> {
            showShortToast(s);
            nav().navigateUp();
        });


    }


    @Override
    public void onStop() {
        if (Utils.isAppForeground() && !mSharedViewModel.isLoading.getValue()) {
            mViewModel.startCode.set(false);
        }
        super.onStop();
    }

    @Override
    public void onDestroy() {
        mViewModel.startCode.set(false);
        super.onDestroy();
    }


    public class ClickProxy {
        public void back() {
            nav().navigateUp();
        }

        public void submit() {
            String mPhone = mViewModel.phone.get();
            if (TextUtils.isEmpty(mPhone)) {
                showShortToast("请输入手机号码");
                return;
            }
            if (mPhone.length() != 11) {
                showShortToast("请输入11位手机号码");
                return;
            }

            String mBankNumber = mViewModel.bankNumber.get();
            if (TextUtils.isEmpty(mBankNumber)) {
                showShortToast("请输入银行卡号");
                return;
            }
            String chiKaRen = mViewModel.chiKaRen.get();
            if (TextUtils.isEmpty(chiKaRen)) {
                showShortToast("请输入持卡人");
                return;
            }

            String shenFenZhen = mViewModel.shenFenZhen.get();
            if (TextUtils.isEmpty(shenFenZhen)) {
                showShortToast("请输入持卡人身份证");
                return;
            }
//            String anQuanMa = mViewModel.anQuanMa.get();
//            if (TextUtils.isEmpty(anQuanMa)) {
//                showShortToast("请输入信用卡安全码");
//                return;
//            }
//            String youxiaoqi = mViewModel.youxiaoqi.get();
//            if (TextUtils.isEmpty(youxiaoqi)) {
//                showShortToast("请选择有效期");
//                return;
//            }
            String orderCode = mViewModel.orderCode.get();
            if (TextUtils.isEmpty(orderCode)) {
                showShortToast("请重新获取验证码");
                return;
            }
            Merchantservice.credit_card.Builder builder = Merchantservice.credit_card.newBuilder();
            builder.setCard(mViewModel.bankNumber.get());
            builder.setMobile(mViewModel.phone.get());
//            builder.setCvv(mViewModel.anQuanMa.get());
//            builder.setValidTime(mViewModel.youxiaoqi.get());
            builder.setCaptcha(mViewModel.code.get());
            builder.setOrderId(mViewModel.orderCode.get());
            builder.setName(mViewModel.chiKaRen.get());
            builder.setIdCard(mViewModel.shenFenZhen.get());
            builder.setIsVip("1");
            NetworkManager.INSTANCE.post(Apis.credit_limit, builder.build().toByteArray(), new OnRequestCallBack() {
                @Override
                public void onOk(byte[] bytes) {
                }

                @Override
                public void onError(int code, String errorMessage) {

                    showShortToast(errorMessage);
                    if (code == 200)  nav().navigateUp();
                }
            });


        }

        public void selectTime() {
            if (mViewModel.monthDialog == null) {
                SelectMonthDialog.Builder builder = new SelectMonthDialog.Builder(mActivity);
                builder.setYearAndMonth(Integer.valueOf(mViewModel.year.get()), Integer.valueOf(mViewModel.month.get()))
                        .setOnDialogClickListener((view, month) -> {
                            String[] split = month.split("-");
                            mViewModel.year.set(split[0]);
                            mViewModel.month.set(split[1]);
                            mViewModel.youxiaoqi.set(split[0] + "-" + split[1]);
                        });
                mViewModel.monthDialog = builder.build();
                mViewModel.monthDialog.setCancelable(true);
            }
            mViewModel.monthDialog.show(getChildFragmentManager());
        }


        public void getCode() {
            String mPhone = mViewModel.phone.get();
            if (TextUtils.isEmpty(mPhone)) {
                showShortToast("请输入手机号码");
                return;
            }
            if (mPhone.length() != 11) {
                showShortToast("请输入11位手机号码");
                return;
            }

            String mBankNumber = mViewModel.bankNumber.get();
            if (TextUtils.isEmpty(mBankNumber)) {
                showShortToast("请输入银行卡号");
                return;
            }
            String chiKaRen = mViewModel.chiKaRen.get();
            if (TextUtils.isEmpty(chiKaRen)) {
                showShortToast("请输入持卡人");
                return;
            }

            String shenFenZhen = mViewModel.shenFenZhen.get();
            if (TextUtils.isEmpty(shenFenZhen)) {
                showShortToast("请输入持卡人身份证");
                return;
            }
//            String anQuanMa = mViewModel.anQuanMa.get();
//            if (TextUtils.isEmpty(anQuanMa)) {
//                showShortToast("请输入信用卡安全码");
//                return;
//            }
//            String youxiaoqi = mViewModel.youxiaoqi.get();
//            if (TextUtils.isEmpty(youxiaoqi)) {
//                showShortToast("请选择有效期");
//                return;
//            }
            Merchantservice.credit_card.Builder builder = Merchantservice.credit_card.newBuilder();
            builder.setCard(mBankNumber);
//            builder.setValidTime(youxiaoqi);
//            builder.setCvv(anQuanMa);
            builder.setMobile(mPhone);
            builder.setIsVip("1");
            builder.setName(chiKaRen);
            builder.setIdCard(shenFenZhen);
            Merchantservice.credit_card data = builder.build();
            NetworkManager.INSTANCE.post(Apis.credit_send, data.toByteArray(), new OnRequestCallBack() {
                @Override
                public void onOk(byte[] bytes) throws InvalidProtocolBufferException {
                    mViewModel.startCode.set(true);
                    Merchantservice.credit_card credit_card = Merchantservice.credit_card.parseFrom(bytes);
                    mViewModel.orderCode.set(credit_card.getOrderId());
                }

                @Override
                public void onError(int code, String errorMessage) {
                    if (code == 200) {
                        mViewModel.startCode.set(true);
                    } else {
                        showShortToast(errorMessage);
                    }

                }
            });
        }


        public void scan()
        {
            OcrSDKKit.getInstance().startProcessOcrResultEntity(mActivity,
                    OcrType.BankCardOCR, null, BankCardOcrResult.class,
                    new ISdkOcrEntityResultListener<BankCardOcrResult>() {
                        @Override
                        public void onProcessSucceed(BankCardOcrResult result, String base64Str) {
                            Log.e("识别", "IdCardOcrResult:" + result.toString()); // OCR 识别成功 IdCardOcrResult
                            mViewModel.bankNumber.set(result.getCardNo());
                        }

                        @Override
                        public void onProcessFailed(String errorCode, String message, String requestId) {
                            showShortToast("识别失败，请重新识别");
//                           showShortToast(message);
                        }
                    });
        }
    }
}
